<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form ref="ruleForm" :rules="rules" :model="ruleForm" label-width="120px" class="el-form">
            <el-form-item label="模板名称" prop="templateName">
                <el-input v-model="ruleForm.templateName" class="w100p" clearable placeholder="请输入模板名称" />
            </el-form-item>
            <el-form-item label="数据类型" prop="dataTypeId">
                <el-select v-model="ruleForm.dataTypeId" class="w100p" clearable placeholder="请选择数据类型"
                    @change="addDataType">
                    <el-option v-for="(item, index) in dataTypeList" :key="index" :value="item.dataTypeId"
                        :label="item.dataTypeName" />
                </el-select>
            </el-form-item>
            <el-form-item label="发送间隔(分钟)" prop="sendingInterval">
                <el-input type="number" class="w100p" v-model="ruleForm.sendingInterval" clearable placeholder="请输入发送间隔" />
            </el-form-item>
            <el-form-item label="滤波类型" prop="filterType">
                <el-select v-model="ruleForm.filterType" class="w100p" clearable>
                    <el-option v-for="(item, index) in filterTypeList" :key="index" :value="item.name" :label="item.name" />
                </el-select>
            </el-form-item>
            <el-form-item label="滤波值" prop="filterValue">
                <el-input type="number" class="w100p" v-model="ruleForm.filterValue" clearable placeholder="请输入滤波值" />
            </el-form-item>
            <el-form-item label="告警通知配置">
                <el-select v-model="ruleForm.noticeConfigNo" class="w100p" clearable>
                    <!-- @change="tifierChange" -->
                    <el-option v-for="(item, index) in contactmanList" :key="index" :value="item.noticeConfigNo"
                        :label="item.noticeConfigName" />
                </el-select>
            </el-form-item>
            <el-form-item label="上限列表">
                <div v-if="addEditFlag == 'add' ||
                    addEditFlag == 'edit'
                    ">
                    <div class="line w100p">
                        <el-input class="valueItem" v-model="basetopList.levelName" clearable placeholder="级别名称" />
                        <el-input class="valueItem" v-model="basetopList.thresholdValue" clearable type="number"
                            placeholder="级别阈值" />
                        <el-select class="valueItem" v-model="basetopList.alarmTypeId">
                            <el-option v-for="(item, index) in alarmTypeList" :key="index" :label="item.alarmTypeName"
                                :value="item.alarmTypeId" />
                        </el-select>
                        <div class="line-click" @click="addtopList()">
                            <i class="el-icon-plus"></i>
                        </div>
                    </div>
                    <div v-for="(item, index) in nowtopList" :key="index" class="line">
                        <el-input class="valueItem" v-model="nowtopList[index].levelName" clearable placeholder="级别名称" />
                        <el-input class="valueItem" v-model="nowtopList[index].thresholdValue" clearable type="number"
                            placeholder="级别阈值" />
                        <el-select class="valueItem" v-model="nowtopList[index].alarmTypeId">
                            <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                                :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
                        </el-select>
                        <div class="line-click" @click="deltopList(index)">
                            <i class="el-icon-minus"></i>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="下限列表">
                <div v-if="addEditFlag == 'add' ||
                    addEditFlag == 'edit'
                    ">
                    <div class="line w100p">
                        <el-input class="valueItem" v-model="basebottomList.levelName" clearable placeholder="级别名称" />
                        <el-input class="valueItem" v-model="basebottomList.thresholdValue" type="number" clearable
                            placeholder="级别阈值" />
                        <el-select class="valueItem" v-model="basebottomList.alarmTypeId">
                            <el-option v-for="(item, index) in alarmTypeList" :key="index" :label="item.alarmTypeName"
                                :value="item.alarmTypeId" />
                        </el-select>
                        <div class="line-click" @click="addbottomList()">
                            <i class="el-icon-plus"></i>
                        </div>
                    </div>
                    <div v-for="(item, index) in nowbottomList" :key="index" class="line w100p">
                        <el-input class="valueItem" v-model="nowbottomList[index].levelName" clearable placeholder="级别名称" />
                        <el-input class="valueItem" v-model="nowbottomList[index].thresholdValue" type="number" clearable
                            placeholder="级别阈值" />
                        <el-select class="valueItem" v-model="nowbottomList[index].alarmTypeId">
                            <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                                :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
                        </el-select>
                        <div class="line-click" @click="delbottomList(index)">
                            <i class="el-icon-minus"></i>
                        </div>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import alarmTemplateConfiguratio from '@/api/monitoringAlarmManagement/alarmTemplateConfiguratio.js';
import contactreq from '@/api/monitoringAlarmManagement/system-notification-configuration.js';

export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        }
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0数！'))
            }
        }
        return {
            filterTypeList: [
                {
                    name: '时间'
                },
                {
                    name: '次数'
                }
            ],
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            qitacontactmanId: '',
            zhuyaocontactmanId: '',
            checkedGroupone: [],
            checkedGrouptwo: [],
            alarmTypeList: [],
            contactmanList: [],
            dataTypeList: [],
            basetopList: [],
            basebottomList: [],
            nowtopList: [],
            nowbottomList: [],
            rules: {
                templateName: [
                    {
                        required: true,
                        message: '模板名称不能为空！',
                        trigger: ['change', 'blur']
                    }
                ],
                dataTypeId: [
                    {
                        required: true,
                        message: '数据类型不能为空！',
                        trigger: ['change', 'blur']
                    }
                ],
                sendingInterval: [
                    { required: true, validator: validatorNumber, trigger: ['change', 'blur'] }
                ],
                filterType: [
                    {
                        required: true,
                        message: '滤波类型不能为空！',
                        trigger: ['change', 'blur']
                    }
                ],
                filterValue: [
                    { required: true, validator: validatorNumber, trigger: ['change', 'blur'] }
                ]
            },
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },
    
    mounted() { },
    methods: {
        initData() {
            this.getselectlist();
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = alarmTemplateConfiguratio.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = alarmTemplateConfiguratio.edit
                this.addEditName = '编辑';
                this.handleEdit(this.ruleForm);
            }
        },
        handleEdit(row) {
            if (row.alarmTemplateId) {
                this.ruleForm = {
                    alarmTemplateId: row.alarmTemplateId,
                    templateName: row.templateName,
                    sendingInterval: row.sendingInterval,
                    filterValue: row.filterValue,
                    filterType: row.filterType,
                    dataTypeId: row.dataTypeId,
                    dataTypeName: row.dataTypeName,
                    noticeConfigNo: row.noticeConfigNo
                }
                this.ruleForm = { ...this.ruleForm }
                alarmTemplateConfiguratio.getalarmTypelist(row.dataTypeId).then(res => {
                    let data = res.data
                    this.chancealarmtype(data)
                })
                this.addDataType(row.dataTypeId)
                row.alarmTemplateThresholdList.forEach(item => {
                    if (item.charge == true) {
                        this.zhuyaocontactmanId = item.alarmContactId
                        this.checkedGroupone = []
                        // 联系方式的赋值
                        if (item.sendPhone == true) {
                            this.checkedGroupone.push(0)
                        }
                        if (item.sendEmail == true) {
                            this.checkedGroupone.push(1)
                        }
                        if (item.sendWeChat == true) {
                            this.checkedGroupone.push(2)
                        }
                    }
                    if (item.charge == false) {
                        this.qitacontactmanId = item.alarmContactId
                        this.checkedGrouptwo = []
                        // 联系方式的赋值
                        if (item.sendPhone == true) {
                            this.checkedGrouptwo.push(0)
                        }
                        if (item.sendEmail == true) {
                            this.checkedGrouptwo.push(1)
                        }
                        if (item.sendWeChat == true) {
                            this.checkedGrouptwo.push(2)
                        }
                    }
                })
                let mainlist = row.alarmTemplateThresholdList
                // 上限列表和下限列表的赋值
                this.basetopList = {
                    levelName: '',
                    alarmTypeId: '',
                    thresholdType: 'max',
                    thresholdValue: ''
                }
                this.nowtopList = []
                this.basebottomList = {
                    levelName: '',
                    alarmTypeId: '',
                    thresholdType: 'min',
                    thresholdValue: ''
                }
                this.nowbottomList = []
                if (mainlist) {
                    for (var i = 0; i < mainlist.length; i++) {
                        if (mainlist[i].thresholdType == 'max') {
                            if (this.basetopList.levelName.length == 0) {
                                this.basetopList = mainlist[i]
                            } else {
                                this.nowtopList.push(mainlist[i])
                            }
                        } else if (mainlist[i].thresholdType == 'min') {
                            if (this.basebottomList.levelName.length == 0) {
                                this.basebottomList = mainlist[i]
                            } else {
                                this.nowbottomList.push(mainlist[i])
                            }
                        }
                    }
                }
            }
        },
        // 获取下拉数据
        getselectlist() {
            // 获取所有数据类型
            alarmTemplateConfiguratio.getalldatalist().then(res => {
                this.dataTypeList = res.data
            })
            // 获取所有联系人
            contactreq.querybycondition({ organizationNo: sessionStorage.organizationNo }).then(res => {
                this.contactmanList = res.data
            })
        },
        // 将选择的数据类别添加到表单中 --获取告警类型列表
        addDataType(e) {
            this.alarmTypeList = []
            this.basetopList = []
            this.basebottomList = []
            this.nowbottomList = []
            this.nowtopList = []
            this.dataTypeList.forEach(el => {
                if (el.dataTypeId == e) {
                    this.ruleForm.dataTypeId = el.dataTypeId
                    this.ruleForm.dataTypeName = el.dataTypeName
                }
            })
            alarmTemplateConfiguratio.getalarmTypelist(e).then(res => {
                let data = res.data
                this.chancealarmtype(data)
            })
        },
        // 处理数据类型数据
        chancealarmtype(list) {
            let newlist = []
            list.forEach((item, index) => {
                newlist.push(item.alarmType)
            })
            this.alarmTypeList = newlist
        },
        addtopList() {
            let addvalue = {
                alarmTypeId: '',
                levelName: '',
                thresholdType: 'max',
                thresholdValue: ''
            }
            this.nowtopList.push(addvalue)
        },
        // 删除一条上限数据
        deltopList(i) {
            this.nowtopList.splice(i, 1)
        },
        // 添加一条下限数据
        addbottomList() {
            let addvalue = {
                alarmTypeId: '',
                levelName: '',
                thresholdType: 'min',
                thresholdValue: ''
            }
            this.nowbottomList.push(addvalue)
        },
        // 添加一条下限数据
        delbottomList(i) {
            this.nowbottomList.splice(i, 1)
        },
        // 获取下拉数据
        getselectlist() {
            // 获取所有数据类型
            alarmTemplateConfiguratio.getalldatalist().then(res => {
                this.dataTypeList = res.data
            })
            // 获取所有联系人
            contactreq
                .querybycondition({ organizationNo: sessionStorage.organizationNo })
                .then(res => {
                    this.contactmanList = res.data
                })
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let addparams = {};
                    let editparams = {};
                    if (this.addEditFlag == 'edit') {
                        editparams = {
                            alarmTemplateSendMapperList: [
                                // 主要联系人
                                {
                                    alarmContactId: this.zhuyaocontactmanId,
                                    charge: true,
                                    sendPhone: false,
                                    sendEmail: false,
                                    sendWeChat: false
                                },
                                // 其他联系人
                                {
                                    alarmContactId: this.qitacontactmanId,
                                    charge: false,
                                    sendPhone: false,
                                    sendEmail: false,
                                    sendWeChat: false
                                }
                            ],
                            alarmTemplateThresholdList: [],
                            ...this.ruleForm
                        }
                        if (editparams.alarmTemplateSendMapperList == []) {
                            delete editparams.alarmTemplateSendMapperList
                        }
                        this.basetopList['thresholdType'] = 'max'
                        this.basebottomList['thresholdType'] = 'min'
                        let newlevellist = [
                            // 上限数据
                            { ...this.basetopList },
                            ...this.nowtopList,
                            { ...this.basebottomList },
                            // 下限数据
                            ...this.nowbottomList
                        ]
                        newlevellist.forEach(el => {
                            editparams['alarmTemplateThresholdList'].push(el)
                        })
                        if (newlevellist == []) {
                            delete editparams.alarmTemplateThresholdList
                        }
                    } else if (this.addEditFlag == 'add') {
                        addparams = {
                            alarmTemplateSendMapperList: [],
                            alarmTemplateThresholdList: [],
                            ...this.ruleForm
                        }
                        if (addparams.alarmTemplateSendMapperList == []) {
                            delete addparams.alarmTemplateSendMapperList
                        }
                        this.basetopList['thresholdType'] = 'max'
                        this.basebottomList['thresholdType'] = 'min'
                        let newlevellist = [
                            // 上限数据
                            { ...this.basetopList },
                            ...this.nowtopList,
                            { ...this.basebottomList },
                            // 下限数据
                            ...this.nowbottomList
                        ]
                        newlevellist.forEach(el => {
                            addparams['alarmTemplateThresholdList'].push(el)
                        })
                        if (newlevellist == []) {
                            delete addparams.alarmTemplateThresholdList
                        }
                    }
                    let params = this.addEditFlag == 'add' ? addparams : editparams
                    this.addEditApi({ ...params }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })

                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.alarmTypeList = [];
            this.contactmanList = [];
            this.dataTypeList = [];
            this.basetopList = [];
            this.basebottomList = [];
            this.nowtopList = [];
            this.nowbottomList = [];
            this.checkedGroupone = [];
            this.checkedGrouptwo = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    align-items: center;

    .valueItem {
        width: calc(100% / 3)
    }

    .line-click {
        width: 90px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: snow 1px solid;
        border-radius: 50%;
        margin-bottom: 10px;
        margin-top: 5px;
        margin-left: 5px;
        cursor: pointer;
    }
}
</style>
  